import {
  BadRequestException,
  Inject,
  Injectable,
  Logger,
} from '@nestjs/common';
import { HttpEnum } from 'src/enum/http.enum';
import { SmsDto } from 'src/pojo/dto/sms.dto';
import { CaptchaVo } from 'src/pojo/vo/captcha.vo';
import { CaptchaTool } from 'src/utils/CaptchaTool';
import { RandomTool } from 'src/utils/RandomTool';
import { RedisClient } from 'src/utils/module/redis.module';
import { SmsService } from 'src/utils/module/sms.module';

@Injectable()
export class NotifyService {
  private readonly logger = new Logger();

  @Inject()
  private redisClient: RedisClient;

  @Inject()
  private captchaTool: CaptchaTool;

  @Inject()
  private randomTool: RandomTool;

  @Inject()
  private smsService: SmsService;

  // 获取图形验证码
  async captcha(key: string, type: string): Promise<CaptchaVo> {
    const svgCaptcha = await this.captchaTool.captche();
    this.redisClient.set(`${type}:captcha:${key}`, svgCaptcha.text, 60 * 5);
    return { captcha: svgCaptcha.data };
  }

  // 获取短信验证码
  async sendSmsCode(smsDto: SmsDto, key: string) {
    if (!(await this.redisClient.exists(`${smsDto.type}:captcha:${key}`))) {
      throw new BadRequestException(HttpEnum.NEED_CAPTCHA);
    }
    const captcha = await this.redisClient.get(`${smsDto.type}:captcha:${key}`);
    if (captcha.toLowerCase() !== smsDto.captcha.toLowerCase()) {
      throw new BadRequestException(HttpEnum.CAPTCHA_INCORRECT);
    }
    if (await this.redisClient.exists(`${smsDto.type}:sms:${smsDto.phone}`)) {
      throw new BadRequestException(HttpEnum.DONT_REQUEST_CAPTCHA_FREQUENTLY);
    }
    const code = this.randomTool.randomCode();
    try {
      await this.smsService.sendSms(smsDto.phone, `${code}`);
      await this.redisClient.set(
        `${smsDto.type}:sms:${smsDto.phone}`,
        `${code}`,
        60 * 5,
      );
    } catch (error) {
      throw new BadRequestException(error);
    }
  }
}
